<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>4_$watch监听数据变化</title>
    <script src="../lib/angularjs.js"></script>
</head>

<body ng-app="myApp" ng-controller="myCtrl">
    <!-- 监听单个变量 -->
    <input style="width:400px" type="text" ng-model="val" placeholder="请输入的内容不超过5个字符。">
    <span ng-style="{ color: 'red'}">{{error}}</span>
    <!-- 监听多个变量，val+val2 -->
    <input type="text" ng-model="val2">
    <!-- 关闭$watch -->
    <button ng-click="cancel()">关闭$watch</button>
    <!-- 监听复杂引用类型 -->
    <input type="text" ng-model="arr[0]">
    <input type="text" ng-model="obj.name">
</body>
<script>
    const myApp = angular.module("myApp", [])
    myApp.controller("myCtrl", ["$scope", function ($scope) {
        $scope.val = ""
        $scope.val2 = ""
        let cancelWatch = $scope.$watch("val+val2", function (newVal, oldVal) {
            // 只要val或val2任意一个发生变化都会触发监听函数。
            console.log("newVal：", newVal);
            console.log("oldVal：", oldVal);
            $scope.error = newVal.length > 5 ? "你输入的字符超过5个，请重新输入" : ""
        })
        $scope.cancel = function () {
            cancelWatch()
        }

        $scope.arr = [1]
        $scope.obj = { name: 123 }
        $scope.$watch("arr", function (newArr, oldArr) {
            // 深度监听数组
            console.log("newArr：", newArr);
            console.log("oldArr：", oldArr);
        }, true)
        $scope.$watch("obj", function (newObj, oldObj) {
            // 深度监听对象
            console.log("newObj：", newObj);
            console.log("oldObj：", oldObj);
        }, true)
    }])
</script>

</html>